IF (OBJECT_ID('Groups')IS NOT NULL)
DROP TABLE Groups;

CREATE TABLE loghog..Groups
(ID int IDENTITY(1,1) not null primary key,
Name nvarchar(60),
CanRead bit default 0,
CanAdd bit default 0,
CanExport bit default 0,
CanImport bit default 0,
CanAddField bit default 0,
CanDelField bit default 0,
CanAddUsers bit default 0,
CanDelUsers bit default 0,
CanCreateGroups bit default 0,
CanDelGroups bit default 0,
CanCreateJournals bit default 0,
CanDelJournals bit default 0);

IF (OBJECT_ID('Type')IS NOT NULL)
DROP TABLE Type;

CREATE TABLE loghog..Type
(ID int IDENTITY(1,1) not null primary key,
Name nvarchar(30),
Description nvarchar(MAX));

IF (OBJECT_ID('Users')IS NOT NULL)
DROP TABLE Users;

CREATE TABLE loghog..Users
(ID int IDENTITY(1,1) not null primary key,
Name nvarchar(60),
Password nvarchar(255),
GroupsID int foreign key references Groups(ID));

IF (OBJECT_ID('Journal')IS NOT NULL)
DROP TABLE Journal;

CREATE TABLE loghog..Journal
(ID int IDENTITY(1,1) not null primary key,
Name nvarchar(80),
UserID int foreign key references Users(ID),
Encryption bit DEFAULT 0);

IF (OBJECT_ID('Journal_Users')IS NOT NULL)
DROP TABLE Journal_Users;

CREATE TABLE loghog..Journal_Users
(ID int IDENTITY(1,1) not null primary key,
JournalID int foreign key references Journal(ID),
UsersID int foreign key references Users(ID));

IF (OBJECT_ID('Journal_Groups')IS NOT NULL)
DROP TABLE Journal_Groups;

CREATE TABLE loghog..Journal_Groups
(ID int IDENTITY(1,1) not null primary key,
JournalID int foreign key references Journal(ID),
GroupsID int foreign key references Groups(ID));

IF (OBJECT_ID('Field')IS NOT NULL)
DROP TABLE Field;

CREATE TABLE loghog..Field
(ID int IDENTITY(1,1) not null primary key,
Name nvarchar(80),
NameRus nvarchar(80),
Description nvarchar(MAX),
DataCreation datetime DEFAULT GETDATE(),
AgreementAuthor nvarchar(60),
TypeID int foreign key references Type(ID));

IF (OBJECT_ID('Journal_Field')IS NOT NULL)
DROP TABLE Journal_Field;

CREATE TABLE loghog..Journal_Field
(ID int IDENTITY(1,1) not null primary key,
JournalID int foreign key references Journal(ID),
FieldID int foreign key references Field(ID));

IF (OBJECT_ID('Value')IS NOT NULL)
DROP TABLE Value;

CREATE TABLE loghog..Value
(ID int IDENTITY(1,1) not null primary key,
BLOB varchar(MAX),
Time datetime DEFAULT GETDATE(),
JournalID int foreign key references Journal(ID),
Deleted bit DEFAULT 0,
Draft bit DEFAULT 0);

IF (OBJECT_ID('Field_Value')IS NOT NULL)
DROP TABLE Field_Value;

CREATE TABLE loghog..Field_Value
(ID int IDENTITY(1,1) not null primary key,
FieldID int foreign key references Field(ID),
ValueID int foreign key references Value(ID));

CREATE TABLE loghog..Tags
(ID int IDENTITY(1,1) not null primary key,
Name nvarchar(MAX),
JournalID int foreign key references Journal(ID));